package com.yq.cp.config;

import com.yq.cp.entity.common.ApiResult;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.stream.Collectors;


/**
 * controller 增强器
 *
 * @author sam
 * @since 2017/7/17
 */
@ControllerAdvice
public class MyControllerAdvice {

    private static final Logger log = LogManager.getLogger(MyControllerAdvice.class);
    /**
     * 拦截捕捉自定义异常 MyException.class
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = MyException.class)
    public ApiResult myErrorHandler(MyException ex) {

        //最后执行结束需要将ThreadLocal中的信息删除  不删除会有内存泄露的风险
        UserThreadLocal.remove();
        log.info("自定义异常:"+ex.getMsg());
        return ApiResult.error(ex.getCode(),ex.getMsg());
    }

    /**
     * 全局异常捕捉处理
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public ApiResult errorHandler(Exception ex) {
        log.info("全局异常:"+ex.getMessage());
        ex.printStackTrace();

        //最后执行结束需要将ThreadLocal中的信息删除  不删除会有内存泄露的风险
        UserThreadLocal.remove();
        return ApiResult.error(10003, ex.getMessage());
    }

    //参数校验异常捕捉处理
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public ApiResult exceptionHandler2(MethodArgumentNotValidException e) {
        StringBuilder sb = new StringBuilder();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        String message = allErrors.stream().map(s -> s.getDefaultMessage()).collect(Collectors.joining(";"));
        return ApiResult.error(1002,message);
    }



}
